//
//  CategoryHome.swift
//  SwiftDemo
//
//  Created by changlei on 2020/11/14.
//

import SwiftUI

struct Home: View {
    var categories: [String: [Landmark]] {
        Dictionary(
                grouping: landmarkData,
                by: { $0.category.rawValue }
        )
    }

    var featured: [Landmark] {
        landmarkData.filter {
            $0.isFeatured
        }
    }

    @State var showingProfile = false
    @EnvironmentObject var userData: UserData

    var profileButton: some View {
        Button(action: { self.showingProfile.toggle() }) {
            Image(systemName: "person.crop.circle")
                    .imageScale(.large)
                    .accessibility(label: Text("User Profile"))
                    .padding(.zero)
        }
    }

    var body: some View {
        NavigationView {
            List {
                FeaturedLandmarks(landmarks: featured)
                        .scaledToFill()
                        .frame(height: 260)
                        .clipped()
                        .listRowInsets(EdgeInsets())

                ForEach(categories.keys.sorted(), id: \.self) { key in
                    CategoryRow(categoryName: key, items: categories[key]!)
                }
                        .listRowInsets(EdgeInsets())

                NavigationLink(destination: LandmarkList()) {
                    Text("See All")
                }
            }
                    .navigationBarTitle(Text("Featured"))
                    .navigationBarItems(trailing: profileButton)
                    .sheet(isPresented: $showingProfile) {
                        ProfileHost()
                                .environmentObject(userData)
                    }
        }
                .buttonStyle(BorderlessButtonStyle())
    }
}

struct FeaturedLandmarks: View {
    var landmarks: [Landmark]
    var body: some View {
        // landmarks[0].image.resizable()
        PageView(features.map {
            FeatureCard(landmark: $0)
        })
                // .aspectRatio(1, contentMode: .fit)
                .frame(height: 260, alignment: .center)
    }
}

struct CategoryHome_Previews: PreviewProvider {
    static var previews: some View {
        Home()
                .environmentObject(UserData())
    }
}
